package com.ks.core.validation;

import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author kingdee
 */
@Component
public class ValidationUtil {

    @Resource
    private Validator validator;

    /**
     * 数检家宴
     *
     * @param source 需要校验的实体对象
     * @param groups 校验分组
     * @param <T>    实体类型
     * @return 错误信息集合 没有错误是返货空集合
     */
    public <T> List<String> validate(T source, Class<?>... groups) {
        Set<ConstraintViolation<T>> validate = validator.validate(source, groups);
        if (CollectionUtils.isEmpty(validate)) {
            return Collections.emptyList();
        }
        return validate.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
    }
}
